/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jsf.util;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import entidades.Usuario;
import javax.servlet.http.HttpSession;

/**
 *
 * @author danilo
 */
public class AuthenticationPhaseListener implements PhaseListener {
    /**
    * <p>The outcome to trigger navigation to the login page.</p>
    */
    private static final String LOGIN_OUTCOME = "login";

    /**
    * <p>The outcome to trigger navigation to the welcome page.</p>
    */
    private static final String WELCOME_OUTCOME = "welcome";

    /**
    * <p>The session attribute key used to store an authenticated consultant.</p>
    */
    public static final String AUTHENTICATED_CONSULTANT_KEY = "jsfcrud.timecard.usuario";

    /**
    * <p>Invoke <code>verifyView</code> if the current phase is apply request values or render response.</p>
    */
    public void beforePhase(PhaseEvent event) {
        PhaseId phase = event.getPhaseId();
        if (PhaseId.APPLY_REQUEST_VALUES.equals(phase) || PhaseId.RENDER_RESPONSE.equals(phase)) {
            verifyView(event);
        }
        if(PhaseId.RENDER_RESPONSE.equals(phase)){
            FacesContext contexto = event.getFacesContext();
            HttpSession sesion = (HttpSession)contexto.getExternalContext().getSession(false);
            if(sesion == null){
                contexto.getApplication().getNavigationHandler().handleNavigation(contexto, "", "error");
            }
        }
    }

    /**
    * <p>No-op.</p>
    */
    public void afterPhase(PhaseEvent event) {
    }

    private void verifyView(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        String viewId = context.getViewRoot().getViewId();
        String forwardToOutcome = null;
        if (isForbiddenView(viewId)) {
            JsfUtil.addErrorMessage("No tienes permiso para ver la página solicitada.");
            //change requested view to the welcome view
            //and assume we will forward to that view
            viewId = "/index.xhtml";
            forwardToOutcome = WELCOME_OUTCOME;
        }
        if (getLoggedInUsuario() == null) {
            if (isSecureView(viewId)) {
                forwardToOutcome = LOGIN_OUTCOME;
            }
        }
        if (forwardToOutcome != null) {
            context.getApplication(). getNavigationHandler().handleNavigation(context, null, forwardToOutcome);
        }
    }

    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

    public static Usuario getLoggedInUsuario() {
        return (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(AuthenticationPhaseListener.AUTHENTICATED_CONSULTANT_KEY);
    }

    private boolean isSecureView(String viewId) {
        if (viewId == null) {
            return false;
        }
        if (isUnrestrictedView(viewId)) {
            return false;
        }
        return ("/index.xhtml".equals(viewId) || "/Error.xhtml".equals(viewId) ||"/Informe.xhtml".equals(viewId) ||  viewId.startsWith("/formulario/") || viewId.startsWith("/usuario/") || viewId.startsWith("/rol/") || viewId.startsWith("/rolFormulario/") || viewId.startsWith("/usuarioRol/"));
    }

    private boolean isForbiddenView(String viewId) {
        if (viewId == null) {
            return true;
        }
        //only unrestricted and secure views are permitted
        if (isUnrestrictedView(viewId) || isSecureView(viewId)) {
        return false;
        }
        return true;
    }

    private boolean isUnrestrictedView(String viewId) {
        return "/Login.xhtml".equals(viewId);
    }


}